<template>
  <el-scrollbar class="sidebar-scrollbar">
    <el-menu
      :default-active="activeMenu"
      :collapse="isCollapse"
      :unique-opened="true"
      class="sidebar-menu"
      @select="handleMenuSelect"
    >
      <template v-for="routeItem in permissionRoutes" :key="routeItem.path">
        <!-- 只有一个子路由且不显示父菜单时，直接显示子路由 -->
        <template v-if="hasOneShowingChild(routeItem) && !routeItem.meta?.alwaysShow">
          <el-menu-item
            v-if="onlyOneChild.meta"
            :index="resolvePath(onlyOneChild.path, routeItem.path)"
            class="submenu-title-noDropdown"
          >
            <el-icon v-if="onlyOneChild.meta.icon">
              <component :is="onlyOneChild.meta.icon" />
            </el-icon>
            <template #title>
              <span>{{ onlyOneChild.meta.title }}</span>
            </template>
          </el-menu-item>
        </template>

        <!-- 有多个子路由或需要显示父菜单 -->
        <el-sub-menu v-else :index="routeItem.path" popper-append-to-body>
          <template #title>
            <el-icon v-if="routeItem.meta?.icon">
              <component :is="routeItem.meta.icon" />
            </el-icon>
            <span>{{ routeItem.meta?.title }}</span>
          </template>

          <template v-for="childItem in routeItem.children" :key="childItem.path">
            <el-menu-item v-if="!childItem.hidden" :index="resolvePath(childItem.path, routeItem.path)">
              <el-icon v-if="childItem.meta?.icon">
                <component :is="childItem.meta.icon" />
              </el-icon>
              <template #title>
                <span>{{ childItem.meta?.title }}</span>
              </template>
            </el-menu-item>
          </template>
        </el-sub-menu>
      </template>
    </el-menu>
  </el-scrollbar>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'

defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})

const router = useRouter()
const route = useRoute()

// 当前激活的菜单
const activeMenu = computed(() => {
  const { path } = route
  return path
})

// 过滤后的路由（过滤掉hidden为true的路由）
const permissionRoutes = computed(() => {
  return router.getRoutes().filter(route => {
    return !route.hidden && route.children && route.children.length > 0
  })
})

let onlyOneChild = null

// 判断是否只有一个显示的子路由
const hasOneShowingChild = parent => {
  if (!parent.children) {
    return false
  }

  const showingChildren = parent.children.filter(item => {
    if (item.hidden) {
      return false
    }
    // 临时设置用于后续渲染
    onlyOneChild = item
    return true
  })

  // 当只有一个子路由时，子路由默认显示
  if (showingChildren.length === 1) {
    return true
  }

  // 如果没有子路由要显示，就显示父路由
  if (showingChildren.length === 0) {
    onlyOneChild = { ...parent, path: '', noShowingChildren: true }
    return true
  }

  return false
}

// 解析路径
const resolvePath = (routePath, basePath) => {
  if (routePath.startsWith('/')) {
    return routePath
  }
  return `${basePath}/${routePath}`.replace(/\/+/g, '/')
}

// 菜单选择处理
const handleMenuSelect = key => {
  router.push(key)
}
</script>

<style scoped>
.sidebar-scrollbar {
  height: calc(100vh - 60px);
}

.sidebar-menu {
  border: none;
  height: 100%;
  width: 100% !important;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 240px;
}

/* 修复收缩状态下的图标居中 */
.sidebar-menu.el-menu--collapse .el-menu-item,
.sidebar-menu.el-menu--collapse .el-sub-menu__title {
  text-align: center;
}

.sidebar-menu.el-menu--collapse .el-menu-item .el-icon,
.sidebar-menu.el-menu--collapse .el-sub-menu__title .el-icon {
  margin-right: 0;
  vertical-align: middle;
}

/* 菜单项样式优化 */
.el-menu-item,
.el-sub-menu__title {
  height: 48px;
  line-height: 48px;
}

.el-menu-item .el-icon,
.el-sub-menu__title .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 激活状态样式 */
.el-menu-item.is-active {
  background-color: var(--el-color-primary-light-9) !important;
  color: var(--el-color-primary) !important;
}

.el-menu-item.is-active:before {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  border-right: 3px solid var(--el-color-primary);
}

/* 悬停效果 */
.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 子菜单标题样式 */
.submenu-title-noDropdown {
  position: relative;
}
</style>
